<?php

namespace yisyus\utils;

class Client
{
    private static $client;
    private $response;
    private $body;

    private function initClient($options)
    {
        if (empty(self::$client)) self::$client = new \GuzzleHttp\Client($options);
    }

    /**
     * 获取请求对象
     * @param string $base_uri Base URI is used with relative requests
     * @return $this
     */
    public static function getClient(string $base_uri = '', $headers = []): Client
    {
        $options = [
            'base_uri' => $base_uri,//基URI用于相对请求
            'timeout' => 30,
            'connect_timeout' => 30,
            'verify' => false,
            'http_errors' => false,
            'headers' => [
                'X-REQUESTED-WITH' => 'XMLHttpRequest',
                'User-Agent' => 'Yiyus',
                'Accept' => 'application/json',
            ]
        ];
        if (!empty($headers)) $options['headers'] = array_merge($options['headers'], $headers);
        $client = new Client();
        $client->initClient($options);
        return $client;
    }

    /**
     * 正文主体
     * @return $this
     */
    public function body()
    {
        $this->body = $this->response->getBody();
        return $this;
    }

    /**
     * 读取响应结果
     * @param boolean $type 返回类型 0 原文返回 1 转为数组（注意：必须确保返回值为json字符串才有效，否则抛出异常）
     * @return mixed
     */
    public function content(bool $type = false)
    {
        return $type === true ? json_decode($this->body->getContents(), true) : $this->body->getContents();
    }

    /**
     * get请求
     * @param $uri
     * @param array $params
     * @return $this
     */
    public function get($uri, array $params = [])
    {
        $this->response = self::$client->get($uri, ['query' => $params]);
        return $this;
    }

    /**
     * post请求
     * @param $uri
     * @param array $params
     * @return $this
     */
    public function post($uri, array $params = []): Client
    {
        $this->response = self::$client->post($uri, ['form_params' => $params]);
        return $this;
    }
}